package com.geekhalo.admin.domain.app;

import com.geekhalo.admin.domain.app.create.CreateWebApplicationCommand;
import com.geekhalo.admin.domain.app.create.CreateWebApplicationContext;
import com.geekhalo.admin.domain.app.create.WebApplicationCreatedEvent;
import com.geekhalo.admin.domain.app.disable.DisableWebApplicationContext;
import com.geekhalo.admin.domain.app.disable.WebApplicationDisabledEvent;
import com.geekhalo.admin.domain.app.enable.EnableWebApplicationContext;
import com.geekhalo.admin.domain.app.enable.WebApplicationEnabledEvent;
import com.geekhalo.admin.domain.app.update.UpdateWebApplicationCommand;
import com.geekhalo.admin.domain.app.update.UpdateWebApplicationContext;
import com.geekhalo.admin.domain.app.update.WebApplicationUpdatedEvent;
import com.geekhalo.lego.core.command.support.AbstractAggRoot;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

@Entity
@Table(name = "web_application")
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Setter(AccessLevel.PRIVATE)
public class WebApplication extends AbstractAggRoot { 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String descr;

    private WebApplicationStatus status;

    private String code;


    public static WebApplication create(CreateWebApplicationContext context) {
        WebApplication agg = new WebApplication();
        agg.readFrom(context.getCommand());
        agg.init();
        return agg;
    }


	// 自动生成代码，勿动
	private void readFrom(CreateWebApplicationCommand source){
		if(source.getName() != null){
			this.setName(source.getName());
		}
		if(source.getDesc() != null){
			this.setDescr(source.getDesc());
		}
		if(source.getCode() != null){
			this.setCode(source.getCode());
		}
	}

    private void init() {
        setStatus(WebApplicationStatus.ENABLED);
        addEvent(new WebApplicationCreatedEvent(this));
    }


    public void update(UpdateWebApplicationContext context) {
        readFrom(context.getCommand());
        addEvent(new WebApplicationUpdatedEvent(this));
    }


	// 自动生成代码，勿动
	private void readFrom(UpdateWebApplicationCommand source){
		if(source.getName() != null){
			this.setName(source.getName());
		}
		if(source.getDesc() != null){
			this.setDescr(source.getDesc());
		}
	}


    public void enable(EnableWebApplicationContext context) {
        if (this.getStatus() != WebApplicationStatus.ENABLED) {
            setStatus(WebApplicationStatus.ENABLED);
            addEvent(new WebApplicationEnabledEvent(this));
        }
    }


    public void disable(DisableWebApplicationContext context) {
        if (this.getStatus() != WebApplicationStatus.DISABLED) {
            setStatus(WebApplicationStatus.DISABLED);
            addEvent(new WebApplicationDisabledEvent(this));
        }
    }
}